<?php
/*
 * Copyright (c) 2022.  Liuhongbin All rights reserved.
 * @domain http://dkyx.cc
 * @author liuhongbin <514660094@qq.com>
 */

namespace app\controller\adminapi\platform\app;

use app\controller\adminapi\platform\PlatformController;
use app\common\model\platform\PlatformAppOpen;
use FormBuilder\Driver\CustomComponent;
use hiduoke\services\CloudServer;
use hiduoke\services\FormBuilder as Form;
use think\App;

/**
 * 服务商
 */
class MinAppOpen extends PlatformController
{
    /**
     * @var PlatformAppOpen
     */
    public $model;

    public function __construct(App $app, PlatformAppOpen $model)
    {
        parent::__construct($app);
        $this->model = $model;
        $this->cloud = new CloudServer();
    }

    public function getMinAppOpenList()
    {
        $res = $this->model->getPageList();
        return $this->success($res['count'], $res['data']);
    }

    /**
     * 抖音服务商管理端配置
     * @param $id
     * @param $type
     * @return \think\response\Json
     * @throws \FormBuilder\Exception\FormBuilderException
     */
    public function getMinAppOpenForm($id = 0, $type = 'dy')
    {
        $rule = array();
        //创建表单
        $row = $this->model->findOrEmpty($id);//创建表单
        $form = Form::createForm("/adminapi/platform/min_app/open/save?id=" . $id)->setMethod("POST");
        //新增表单
        $rule[] = Form::input('name', '应用名称', $row['name'] ?? "")->required();
        $rule[] = Form::dkImage('logo', '应用图标', $row['logo'] ?? "")->required();
        $rule[] = Form::input('addon_name', '绑定应用标识', $row['addon_name'] ?? "")->required();
        $rule[] = Form::hidden('type', $type);
        if ($type == 'dy') {
            $rule[] = (new CustomComponent("h3"))->appendChild("模板配置")->prop("style", "margin-bottom:20px");
            $rule[] = Form::input('config_template_id', '模板ID', $row['config']['template_id'] ?? '');
            $rule[] = Form::input('config_user_desc', '描述', $row['config']['user_desc'] ?? '');
            $rule[] = Form::input('config_user_version', '版本号', $row['config']['user_version'] ?? '');
            $rule[] = Form::ElAlert()->title('抖音服务商配置说明')
                ->description('当前功能未对用户开放，仅内部使用')
                ->type('warning')
                ->prop('style', 'margin: 20px 0;')
                ->showIcon(true);
            // 选择默认授权方式
            $rule[] = Form::radio("config_auth_type", "授权方式", $row['config']['auth_type'] ?? 'manual')
                ->button()
                ->size('small')
                ->options([
                        ['label' => '自建小程序（手动配置）', 'value' => 'manual'],
                        ['label' => '用户自由选择配置方式', 'value' => 'auto'],
                        ['label' => '抖音服务商链接授权', 'value' => 'open'],
                    ]
                )->effect(['help' => '当前未对外部用户开放该功能']);
            //开发者ID
            $rule[] = (new CustomComponent("h3"))->appendChild("开发者ID")->prop("style", "margin-bottom:20px");
            $rule[] = Form::dkInput("config_component_appid", "appid", $row['config']['component_appid'] ?? '', '第三方小程序应用 appid')->required();
            $rule[] = Form::dkInput('config_component_appsecret', 'APPSecret', $row['config']['component_appsecret'] ?? '', '第三方小程序应用 APPSecret')->required();
            // 授权流程相关
            $rule[] = (new CustomComponent("h3"))->appendChild("授权流程相关")->prop("style", "margin-bottom:20px");
            if ($id) {
                $oauth_url = request()->domain() . '/dy/open/event/id/' . $id;
                $message_event_url = request()->domain() . '/dy/open/message_event/id/' . $id . '/appid/$APPID$/cgi';
            } else {
                $oauth_url = "请提交保存后打开";
                $message_event_url = "请提交保存后打开";
            }

            $rule[] = Form::dkCopyInput("oauth_url", '授权事件接收 URL', $oauth_url)
                ->appendRule("suffix", Form::getHelp("将当前地址填写至授权事件接收 URL，通过该 URL 接收小程序授权成功通知、授权解除通知，也用于接收 component_ticket"))
                ->disabled(true);

            // 授权后实现业务
            $rule[] = (new CustomComponent("h3"))->appendChild("授权后实现业务")->prop("style", "margin-bottom:20px");
            $rule[] = Form::dkCopyInput("message_event_url", '消息与事件接收 URL', $message_event_url)
                ->appendRule("suffix", Form::getHelp("将当前地址填写至授权事件接收 URL，通过该 URL 接收已授权小程序的消息和事件推送"))
                ->disabled(true);
            $rule[] = Form::dkInput("config_token", "TOKEN", $row['config']['token'] ?? '', '消息验证 TOKEN 服务商在代授权小程序接收到消息后，用来验证信息，最长为 32 位，只能是大小写字母和数字')->required();
            $rule[] = Form::dkInput("config_key", "key", $row['config']['key'] ?? '', '消息加密解密 KEY 服务商在代授权小程序接收到消息后，用来解密消息，必须是长度为 43 的字符串，只能是大小写字母和数字')->required();
        }

        $title = !$id ? "新增" : "编辑";
        $form->setTitle($title)->setRule($rule);
        return $this->success("", Form::getFormData($form));
    }


    public function save()
    {
        $id = input('id', 0);
        $row = $this->model->findOrEmpty($id);
        $formData = getFormData();
        $row->save($formData);
        if ($id) {
            return $this->success("保存成功");
        } else {
            return $this->success('新增成功');
        }
    }

//    /**
//     * 获取授权地址
//     * @param $default_app_id
//     * @return \think\response\Json
//     * @throws \think\db\exception\DataNotFoundException
//     * @throws \think\db\exception\DbException
//     * @throws \think\db\exception\ModelNotFoundException
//     */
//    public function getDouyinGenUrl($default_app_id = 0)
//    {
//        $platform_app = (new PlatformApp())->where(['id' => $default_app_id])->find();
//
//        $platform_app_open = (new PlatformAppOpen())->where(['addon_name' => $platform_app['addon_name']])->find();
//        if (!$platform_app_open) {
//            return $this->error('没有找到当前抖音服务商应用');
//        }
//        $DY = new DouyinOpenApi($platform_app_open['config']);
//        $component_access_token = $platform_app_open['other_data']['component_access_token'] ?? '';
//        $url = $DY->getGenLink($component_access_token, $default_app_id);
//        return $this->success('in', ['url' => $url]);
//    }
}
